package com.bjesc_b2c.app.appraiset.mvp.view.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseFragment;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.mvp.view.activity.LoginActivity;
import com.bjesc_b2c.app.appraiset.utils.UpdateManager;
import com.bjesc_b2c.app.appraiset.widget.dialog.TipDialog;
import com.example.codeutils.utils.AppUtils;
import com.example.codeutils.utils.FileUtils;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.CustomSharedPreferences;
import com.rxretrofit_build.util.MapUtil;

import java.io.File;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;
import master_bean.AppUpdateBean;
import rxretrofit_base.model.FileLoadingBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

import static android.os.Environment.getExternalStorageDirectory;

/**
 * Created by yidong on 2017/6/22.
 */

public class MineFragment extends BaseFragment implements TipDialog.CallBack {

    private ProgressDialog mDialog;
    @Bind(R.id.cc_name)
    TextView nameTv;
    @Bind(R.id.cc_phone)
    TextView phoneTv;
    @Bind(R.id.tv_cache)
    TextView cacheTv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_mine_layout, null);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void initView() {
        nameTv.setText(CustomSharedPreferences.getString(getActivity(), KeyBean.NICK_NAME.valueOf(), KeyBean.FILE_NAME.valueOf()));
        phoneTv.setText(CustomSharedPreferences.getString(getActivity(), KeyBean.USER_NAME.valueOf(), KeyBean.FILE_NAME.valueOf()));
    }

    @Override
    public void initData() {
       String size = FileUtils.getDirSize(new File(getExternalStorageDirectory() + "/Pgs/"));
        cacheTv.setText(size);
    }

    @OnClick({R.id.rlty_update, R.id.tv_exit,R.id.rlty_cache})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlty_update:
                int mVersion_code = AppUtils.getAppVersionCode(getActivity());// 当前的版本号
                getVisern(mVersion_code);
                break;
            case R.id.tv_exit:
                TipDialog exitDialog = new TipDialog(getActivity(), this);
                exitDialog.setMessageText("是否退出当前账号?");
                exitDialog.show();
                break;
            case R.id.rlty_cache:
               boolean isClear =  FileUtils.deleteFilesInDir(new File(getExternalStorageDirectory() + "/Pgs/"));
                if (isClear){
                    String size = FileUtils.getDirSize(new File(getExternalStorageDirectory() + "/Pgs/"));
                    cacheTv.setText(size);
                }
                break;

        }
    }

    @Override
    public void tipCallBack() {
        HashMap<String, Object> build = new MapUtil()
                .put(KeyBean.USER_NAME.valueOf(), "")
                .put(KeyBean.PASSWORD.valueOf(), "")
                .build();
        CustomSharedPreferences.saveString(getActivity(), build, KeyBean.FILE_NAME.valueOf());
        startActivity(new Intent(getActivity(), LoginActivity.class));
        getActivity().finish();
    }

    private void getVisern(int version) {
        HashMap<String, Object> map = new MapUtil()
                .put("version", version)
                .put("url", true).build();
        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(getActivity(), map).create(IApiActivityRequest.class).appVersion(),
                new BaseSubscriber<TokenBean<AppUpdateBean>>(getActivity()) {
                    @Override
                    public void onSuccess(TokenBean<AppUpdateBean> o) {

                        if (o.getData() != null) {
                            Logger.d("  ==" + o.getData().getUrl());
                            String url = o.getData().getUrl();
                            String version_info = "\t\t\t发现新的版本,是否更新？";
                            showProgressDialog();
                            new UpdateManager(getActivity()).showNoticeDialog(version_info, url, mDialog);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        cancelLoading();
                    }

                    @Override
                    public void onStart() {
                       showLoading("版本检测...");
                    }

                    @Override
                    public void onCompleted() {
                     cancelLoading();
                    }
                });
    }

    private void showProgressDialog() {
        mDialog = new ProgressDialog(getActivity());
        mDialog.setTitle("正在下载");
        mDialog.setMax(100);
        mDialog.setIndeterminate(false);
        mDialog.setMessage("请稍候...");
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setCanceledOnTouchOutside(false);
//        mProgressDialog.show();

    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getO() instanceof FileLoadingBean) {
            FileLoadingBean fileLoadingBean = (FileLoadingBean) rxBusBean.getO();
            int progress = (int) (fileLoadingBean.getProgress() * 100 / fileLoadingBean.getTotal());
            mDialog.setProgress(progress);
            if (progress == 99) {
                mDialog.dismiss();
            }
        }
    }

    public void onDestroyView() {
        super.onDestroyView();

    }
}